package com.hejie.videoservice.config;

import com.hejie.common.domain.ResponseResult;
import com.hejie.common.enums.ErrorCode;
import com.hejie.videoservice.exception.VideoNotFoundException;
import com.hejie.videoservice.exception.VideoProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理视频未找到异常
     */
    @ExceptionHandler(VideoNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseResult<Void> handleVideoNotFoundException(VideoNotFoundException e) {
        log.error("Video not found: {}", e.getMessage());
        return ResponseResult.error(ErrorCode.RESOURCE_NOT_FOUND, e.getMessage());
    }

    /**
     * 处理视频处理异常
     */
    @ExceptionHandler(VideoProcessingException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult<Void> handleVideoProcessingException(VideoProcessingException e) {
        log.error("Video processing error: {}", e.getMessage(), e);
        return ResponseResult.error(ErrorCode.VIDEO_PROCESSING_FAILED, e.getMessage());
    }

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException e) {
        Map<String, String> errors = new HashMap<>();
        e.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return ResponseResult.error(ErrorCode.PARAM_VALID_ERROR, "参数验证失败", errors);
    }

    /**
     * 处理权限不足异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResponseResult<Void> handleAccessDeniedException(AccessDeniedException e) {
        log.warn("Access denied: {}", e.getMessage());
        return ResponseResult.error(ErrorCode.ACCESS_DENIED, "权限不足");
    }

    /**
     * 处理通用异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult<Void> handleGeneralException(Exception e) {
        log.error("Unexpected error occurred: {}", e.getMessage(), e);
        return ResponseResult.error(ErrorCode.SYSTEM_ERROR, "系统异常，请联系管理员");
    }
}